/**
 *   This file is part of WiFiStorer.

    WiFiStorer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    WiFiStorer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with WiFiStorer.  If not, see <http://www.gnu.org/licenses/>.
    
    @author Ontic Soluciones
    @license GNU GPLv3
    @copyright 2010 Ontic Soluciones
    @link http://www.ontic.es
    @contact android@ontic.es
 */


package com.Storer;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;


/**
 * Nos ayuda a realizar varios accesos en tiempo de ejecución a nuestra base de datos
 * @author Ontic Soluciones
 *
 */
public class DataBaseHelper extends SQLiteOpenHelper
{
	static SimpleDateFormat formato = new SimpleDateFormat("yyyyMMdd");
	Date fecha = new Date();

    private SQLiteDatabase base; 
 
    private final Context contexto;
 
    /**
     * Constructor de la clase, crea una nueva instancia de DataBaseHelper
     * @param context El contexto de la actividad que lo llama.
     */
    public DataBaseHelper(Context contexto) 
    {
    	super(contexto, "Datos", null, 1);
    	this.contexto = contexto;
        
    }	
 
  /**
     * Crea una nueva base de datos vacía y la enlaza con la nuestra
     * */
    public void createDataBase() throws IOException
    {
    	boolean existe = compruebaBase();
    	if(!existe)
    	{
        	this.getReadableDatabase();
        	try 
        	{
    			copyDataBase();
    		} 
        	catch (IOException e) 
        	{
        		throw new Error(""+R.string.db_error);
        	}
    	}
 
    }
 
    /**
     * Comprueba si la BDD existe para evitar recopiar el archivo cada vez que abrimos la aplicación 
     * @return true si existe, falso si no
     */
    private boolean compruebaBase(){
 
    	SQLiteDatabase checkDB = null;
 
    	try{
    		String myPath = "/data/data/com.example1/databases/Datos";
    		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 
    	}catch(SQLiteException e){
    	}
 
    	if(checkDB != null){
 
    		checkDB.close();
 
    	}
 
    	return checkDB != null ? true : false;
    }
 
    /**
     * Copia la base de datos de la ruta especificada en la recien creada. Para que pueda ser manejada.
     * 
     * */
    private void copyDataBase() throws IOException{
 
    	InputStream myInput = contexto.getAssets().open("Datos");

    	String outFileName = "/data/data/com.example1/databases/Datos";

    	OutputStream myOutput = new FileOutputStream(outFileName);

    	byte[] buffer = new byte[1024];
    	int length;
    	while ((length = myInput.read(buffer))>0){
    		myOutput.write(buffer, 0, length);
    	}

    	myOutput.flush();
    	myOutput.close();
    	myInput.close();
    }
 
    /**
     * Abre la base de datos
     * @throws SQLException
     */
    public void openDataBase() throws SQLException
    {
    	//Open the database
        String myPath = "/data/data/com.example1/databases/Datos";
    	base = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }
 
    /**
     * Cierra la base de datos
     */
    @Override
	public synchronized void close() 
    {
    	    if(base != null)
    		    base.close();
    	    super.close();
	}

	@Override
	public void onCreate(SQLiteDatabase db) 
	{
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
	{
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * Devuelve la base de datos
	 * @return base
	 */
	public SQLiteDatabase dameBD()
	{
		return this.base;
	}
	
 
}